package main

import (
	"database/sql"
	"fmt"
)

func main() {
	// 连接到 SQLite 数据库文件，如果文件不存在，将创建一个新的文件
	db, err := sql.Open("sqlite", "site_db.db")
	if err != nil {
		fmt.Println("Error opening database:", err)
		return
	}
	defer func(db *sql.DB) {
		err := db.Close()
		if err != nil {
			panic(err)
		}
	}(db)

	// 创建一个表
	createTableSQL := `
          CREATE TABLE IF NOT EXISTS users (
             id INTEGER PRIMARY KEY AUTOINCREMENT,
             name TEXT NOT NULL,
             age INTEGER
          );
       `
	_, err = db.Exec(createTableSQL)
	if err != nil {
		fmt.Println("Error creating table:", err)
		return
	}

	// 插入数据
	insertSQL := `
          INSERT INTO users (name, age) VALUES (?,?);
       `
	_, err = db.Exec(insertSQL, "Alice", 30)
	if err != nil {
		fmt.Println("Error inserting data:", err)
		return
	}

	// 查询数据
	rows, err := db.Query("SELECT id, name, age FROM users")
	if err != nil {
		fmt.Println("Error querying data:", err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var id int
		var name string
		var age int
		err = rows.Scan(&id, &name, &age)
		if err != nil {
			fmt.Println("Error scanning row:", err)
			continue
		}
		fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, name, age)
	}
}
